import { AxiosOptions } from "@/types/axios"
import { AxiosRequestConfig } from "axios"

const pendingMap = new Map<string, { controller: AbortController, time: number }>()

const getUrl = (config: AxiosRequestConfig) => {
    return [config.url, config.method].join(':')
}

class AbortAxios {
    // 添加控制器
    public addPending(config: AxiosOptions) {
        this.removePending(config)
        const url = getUrl(config)
        // 创建控制器
        const abortController = new AbortController()
        // 定义对应的signal
        config.signal = abortController.signal
        if (!pendingMap.has(url)) {
            pendingMap.set(url, { controller: abortController, time: Date.now() })
        }
    }

    // 删除控制器
    public removePending(config: AxiosOptions) {
        const url = getUrl(config)
        if (pendingMap.has(url)) {
            const abortController = pendingMap.get(url)!
            if (config.throttle && Date.now() - abortController.time < config.throttle) {
                abortController.controller.abort()
            } else {
                pendingMap.delete(url)
            }
        }
    }
}

export default AbortAxios